﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace BotApp
{
    class Answers {
        /// <summary>
        /// The top answer found in the QnA Service.
        /// </summary>
        [JsonProperty(PropertyName = "answer")]
        public string Answer { get; set; }

        /// <summary>
        /// The score in range [0, 100] corresponding to the top answer found in the QnA    Service.
        /// </summary>
        [JsonProperty(PropertyName = "score")]
        public double Score { get; set; }

        /// <summary>
        /// questions 
        /// </summary>
        [JsonProperty(PropertyName = "questions")]
        public List<string> Questions { get; set; }
    }
    class QnAMakerResult
    {
        [JsonProperty(PropertyName = "answers")]
        public List<Answers> Answers { get; set; }

        public static string QnAMakerFun(string query) {

            string responseString = string.Empty;
            var knowledgebaseId = "b1c38212-7d0c-433b-955f-2bb4de393581"; // Use knowledge base id created.
            var qnamakerSubscriptionKey = "d8c0b953b7d04b71bf7489dd67fc49bf"; //Use subscription key assigned to you.

            Uri qnamakerUriBase = new Uri("https://westus.api.cognitive.microsoft.com/qnamaker/v2.0");
            var builder = new UriBuilder($"{qnamakerUriBase}/knowledgebases/{knowledgebaseId}/generateAnswer");
            var postBody = $"{{\"question\": \"{query}\"}}";
         
            using (WebClient client = new WebClient())
            {
                client.Encoding = System.Text.Encoding.UTF8;
                client.Headers.Add("Ocp-Apim-Subscription-Key", qnamakerSubscriptionKey);
                client.Headers.Add("Content-Type", "application/json");
                responseString = client.UploadString(builder.Uri, postBody);
            }

            QnAMakerResult response;
            try
            {
                response = JsonConvert.DeserializeObject<QnAMakerResult>(responseString);
            }
            catch
            {
                throw new Exception("Unable to deserialize QnA Maker response string.");
            }
            string answer = response.Answers[0].Answer;

            return answer;
        }
    }
   
    
}
